package edu.visualizetion.info.sensorcollection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.NetStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Swap;

public class SigarFactory {

	private static Sigar sigar = null;

	public static Sigar InitSigar() {

		if (sigar == null) {
			sigar = new Sigar();
		}
		return sigar;
	}

	public static Mem getMemory() throws SigarException {
		try {
			return sigar.getMem();
		} catch (SigarException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static CpuPerc getCpu() throws SigarException {
		try {
			return sigar.getCpuPerc();
		} catch (SigarException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static Swap getSwap() throws SigarException {
		try {
			return sigar.getSwap();
		} catch (SigarException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static Pair<Long, Long> getNetRecvSend(String netIp) throws SigarException {
		
		String[] strings = sigar.getNetInterfaceList();
		for (String name : strings) {
			NetInterfaceConfig interfaceConfig = sigar.getNetInterfaceConfig(name);
			if (interfaceConfig.getAddress().equals(netIp)) {
				NetInterfaceStat interfaceStat = sigar.getNetInterfaceStat(name);
				long recv = interfaceStat.getRxBytes();
				long send = interfaceStat.getTxBytes();
				return new Pair<Long, Long>(recv, send);
			}
		}
		
		return null;
	}

	public static NetStat getNet() throws SigarException {
		try {
			return sigar.getNetStat();
		} catch (SigarException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static List<Object> getDisk() throws SigarException {
		try {
			FileSystem[] fileSystems = sigar.getFileSystemList();
			Map<String, Long> diskread = new HashMap<>();
			Map<String, Long> diskwrite = new HashMap<>();
			List<Object> list = new ArrayList<>();
			for (FileSystem fileSystem : fileSystems) {
				String dirName = fileSystem.getDirName();
				FileSystemUsage fileSystemUsage = sigar.getFileSystemUsage(dirName);
				diskread.put(dirName, fileSystemUsage.getDiskReads());
				diskwrite.put(dirName, fileSystemUsage.getDiskWrites());
			}
			list.add(diskread);
			list.add(diskwrite);
			return list;
		} catch (SigarException e) {
			e.printStackTrace();
			throw e;
		}
	}
}
